package net.omnivention.wulumuqi;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
import org.apache.log4j.Logger;

/**
 * Servlet implementation class for Servlet: WuluScriptActionServlet
 *
 */
public class WuluScriptActionServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private final static Logger logger = Logger.getLogger(WuluScriptActionServlet.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		executeAction(request, response, getServletContext());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	void executeAction(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
			throws IOException {
		try {
			BSFManager manager = new BSFManager();
			manager.loadScriptingEngine("jython");
			manager.declareBean("request", request, HttpServletRequest.class);
			manager.declareBean("response", response, HttpServletResponse.class);
			manager.declareBean("session", request.getSession(), HttpSession.class);
			manager.declareBean("out", response.getOutputStream(), ServletOutputStream.class);
			manager.declareBean("servletContext", servletContext, ServletContext.class);

			String scriptURL = request.getParameter("scriptURL");
			if (scriptURL.indexOf("http://") == -1) {
				scriptURL = "file:///" + servletContext.getRealPath(scriptURL);
			}
			String script = WuluUtil.getResource(scriptURL);
			manager.exec("jython", scriptURL, 0, 0, script);
		} catch (BSFException e) {
			logger.error(e, e);
		}
	}
}